package com.example.yc_plugin_learn;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 PlatformView 提供原生view
 */

public class YcPlatformView implements PlatformView, MethodChannel.MethodCallHandler {

    private View view;
    private TextView tv;
    private HashMap args;
    private int viewId;

    /**
     * 通道，用来收flutter消息
     */
    private MethodChannel channel;

    /**
     * 事件通道，用来发消息给flutter
     */
    private EventChannel.EventSink sink;


    public YcPlatformView(Context context, int i, Object o, FlutterPlugin.FlutterPluginBinding binding) {

        //初始值
        args = (HashMap) o;
        viewId = i;

        //处理flutter传过来的消息
        channel = new MethodChannel(binding.getBinaryMessenger(),"yc_plugin_learn_view_" + i);
        channel.setMethodCallHandler(this);

        //主动给flutter发消息
        new EventChannel(binding.getBinaryMessenger(), "yc_plugin_learn_eventChannel_view_" + i).setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object o, EventChannel.EventSink eventSink) {
                sink = eventSink;
            }

            @Override
            public void onCancel(Object o) {
                sink = null;
            }
        });

        //加载原生自定义布局，从布局文件里面映射
        //先敲出R.layout.view_my_flutter，然后再按option + 回车键，选择自动生成view_my_flutter.xml
        view = LayoutInflater.from(context).inflate(R.layout.view_my_flutter,null,false);

        //赋值
        tv = view.findViewById(R.id.tv);
        tv.setText((String)args.get("content"));

        Button btn = view.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> map = new HashMap<>();
                map.put("type", "1");
                sink.success(map);
            }
        });
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void dispose() {

    }

    /**
     * flutter触发
     */
    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (call.method.equals("updateText")) {

            //获取参数
            HashMap map = (HashMap) call.arguments;
            String content = (String) map.get("updateText");
            if (content != null){
                tv.setText(content);
            }

        } else {
            //其他方法事件
        }

    }
}
